import socket
import time
# 创建一个socket对象
sk = socket.socket()

# 绑定ip和端口
sk.bind(('127.0.0.1', 8848))

# 监听
sk.listen()


def index(url):
    with open('index.html', 'rb') as f:
        return f.read()


def home(url):
    ret = '欢迎回家! - {}'.format(url)
    return ret.encode('utf-8')


def help_me(url):
    ret = '再等30年,你又是条好汉! - {}'.format(url)
    return ret.encode('utf-8')


def timer(url):
    now = time.time()
    with open('time.html','r',encoding='utf-8') as f:
        ret = f.read()
        ret = ret.replace('@@time@@',str(now))
        return ret.encode('utf-8')


list1 = [
    ('/index', index),
    ('/home', home),
    ('/help_me', help_me),
    ('/time', timer),
]

# 等待连接
while True:
    conn, addr = sk.accept()

    data = conn.recv(1024)
    url = data.decode('utf-8').split()[1]

    # for i in list1:
    #     if url == i[0]:
    #         ret = i[1](url)
    #         break
    # else:
    #     ret = '被查办了!'.encode('utf-8')

    func = None
    for i in list1:
        if url == i[0]:
            func = i[1]
            break
    if func:
        ret = func(url)
    else:
        ret = '被查办了!'.encode('utf-8')

    conn.send(b'HTTP/1.1 200 OK\r\ncontent-type: text/html; charset=utf-8\r\n\r\n')
    conn.send(ret)

    conn.close()
